package com.nand.module.function.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lzy.okgo.model.HttpParams;
import com.nand.library.base.base.BaseActivity;
import com.nand.library.base.bean.ResponseBean;
import com.nand.library.base.http.MyCallback;
import com.nand.library.base.http.OkGoUtils;
import com.nand.library.base.utils.ObjectUtils;
import com.nand.library.base.utils.SharedPreferencesUtils;
import com.nand.library.greendao.entity.SearchText;
import com.nand.library.greendao.source.TaskLocalDataSource;
import com.nand.library.zxing.activity.CaptureActivity;
import com.nand.library.zxing.activity.CodeUtils;
import com.nand.module.function.R;
import com.nand.module.function.adapter.SearchAdapter;
import com.nand.module.function.bean.NumberBean;
import com.nand.module.function.constant.URL;
import com.nand.module.function.utils.LogUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

@Route(path = "/function/qr/code")
public class FMainActivity extends BaseActivity {

    private static final int REQUEST_CODE = 1010;
    private List<String> list = new ArrayList<>();
    private SearchAdapter mAdapter;
    private String code;
    private EditText etSearch;
    private TaskLocalDataSource dataSource;
    private List<SearchText> searchTexts;
    private RecyclerView mRecyclerView;
    private LinearLayout mShowTips;
    private List<NumberBean.DataListBean> dataList;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataSource = new TaskLocalDataSource(this);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_fmain;
    }

    @Override
    protected boolean isActionBar() {
        return true;
    }

    @Override
    protected void initView() {
        mShowTips = findViewById(R.id.show_tips);
        setTitleText("设备查询");
        etSearch = findViewById(R.id.et_search);
        etSearch.addTextChangedListener(watcher);

        mRecyclerView = findViewById(R.id.rv_list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new SearchAdapter(R.layout.item_text_layout);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ArrayList<String> ls = new ArrayList<>();
                String str = (String) adapter.getData().get(position);
                String searchText = (String) SharedPreferencesUtils.getParam(FMainActivity.this, "SearchText", "");
                if (!ObjectUtils.isEmpty(searchText)) {
                    List<String> s = JSON.parseArray(searchText, String.class);
                    ls.add(str);
                    for (int i = 0; i < s.size(); i++) {
                        if (ls.size() < 10 && !s.get(i).equals(str)) {
                            ls.add(s.get(i));
                        }
                    }
                } else {
                    ls.add(str);
                }
                SharedPreferencesUtils.setParam(FMainActivity.this, "SearchText", JSON.toJSONString(ls));

                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
                bundle.putString(CodeUtils.RESULT_STRING, dataList.get(position).getEquipID());
                bundle.putString(CodeUtils.RESULT_STRING2, dataList.get(position).getOid());
                intent.putExtras(bundle);
                FMainActivity.this.setResult(RESULT_OK, intent);
                FMainActivity.this.finish();
            }
        });
    }


    @Override
    protected void initData() {
        String searchText = (String) SharedPreferencesUtils.getParam(this, "SearchText", "");

       /* if (!ObjectUtils.isEmpty(searchText)) {
            List<String> ls = JSON.parseArray(searchText, String.class);
            list.addAll(ls);
            mAdapter.addData(list);
            mRecyclerView.setVisibility(View.VISIBLE);
        }*/
    }

    public void onClick(View view) {
        Intent intent = new Intent(FMainActivity.this, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE);
    }


    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.length() > 0) {
                getSearchInfo(editable.toString(),0);
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    final String result = bundle.getString(CodeUtils.RESULT_STRING);
                    HttpParams params = new HttpParams();
                    params.put("equipID", result);
                    OkGoUtils.getInstance().post(this, URL.EFFECT_EQUIPID, params, 1, false, new MyCallback() {
                        @Override
                        public void onSuccess(ResponseBean response, int id) {
                            if (200 == response.getCode()){
                                getSearchInfo(result,1);
                            }else {
                                showToast("无效设备编码");
                            }
                        }

                        @Override
                        public void onError(Throwable e, int id) {

                        }
                    });


                    //Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();


                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(FMainActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private void getSearchInfo(String text, final int type) {
        HttpParams params = new HttpParams();
        params.put("equipID", text);
        params.put("current", "1");
        params.put("size", "10");
        OkGoUtils.getInstance().post(this, URL.GET_EQUIPMENT_INFO, params, 0, false, new MyCallback() {
            @Override
            public void onSuccess(ResponseBean response, int id) {
                if (response.getCode() == 200) {
                    String dataInfo = response.getDataInfo().toString();
                    LogUtils.e("ab======="+dataInfo);
                    NumberBean bean = JSON.parseObject(dataInfo, NumberBean.class);
                    dataList = bean.getDataList();
                    list.clear();
                    for (int i = 0; i < dataList.size(); i++) {
                        list.add(dataList.get(i).getEquipID());
                    }
                    mAdapter.replaceData(list);
                } else {
                    showToast(response.getMsg());
                }
                if (list.size() >= 0) {
                    mShowTips.setVisibility(View.GONE);
                    mRecyclerView.setVisibility(View.VISIBLE);

                    if (1 == type){
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_SUCCESS);
                        bundle.putString(CodeUtils.RESULT_STRING, dataList.get(0).getEquipID());
                        bundle.putString(CodeUtils.RESULT_STRING2, dataList.get(0).getOid());
                        intent.putExtras(bundle);
                        FMainActivity.this.setResult(RESULT_OK, intent);
                        FMainActivity.this.finish();
                    }

                } else {
                    mShowTips.setVisibility(View.VISIBLE);
                    mRecyclerView.setVisibility(View.GONE);
                   /* if (1 == type){
                        Toast.makeText(FMainActivity.this, "无效设备编码", Toast.LENGTH_LONG).show();
                    }*/
                }
            }

            @Override
            public void onError(Throwable e, int id) {

            }
        });
    }

}
